<?php
declare(strict_types=1);

namespace Core\HyperfUnit;

use Hyperf\DbConnection\Db;
use Zms\Unit\Arr;
use function Hyperf\Config\config;

/**
 * 数据库工具
 */
class DataBase
{

    /**
     * 获取数据库字典
     * @return array
     */
    public static function dictionary(): array
    {
        return Callback::cache(__METHOD__, function () {
            $dictionary = [];
            foreach (self::table() as $database => $item) {
                $group = [];
                $tabinfo = Arr::map($item['list'], 'Name', '*');
                $result = DB::connection($item['connection'])->select("SELECT TABLE_NAME AS `table`,`COLLATION_NAME` AS `collation`, COLUMN_NAME AS `field`, COLUMN_TYPE AS `type`, CASE IFNULL(COLUMN_DEFAULT,'Null') WHEN '' THEN '空字符串' WHEN 'Null' THEN 'NULL' ELSE COLUMN_DEFAULT END  AS `default`, CASE IS_NULLABLE WHEN 'YES' THEN '是' ELSE '否' END AS `is_null`, COLUMN_COMMENT AS `comment` FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='$database'");
                foreach ($result as $row) {
                    if (!isset($group[$row->table])) {
                        $group[$row->table] = [
                            'table' => $row->table, 'engine' => $tabinfo[$row->table]['Engine'], 'comment' => $tabinfo[$row->table]['Comment'], 'collation' => $tabinfo[$row->table]['Collation'], 'database' => $item['database'], 'connection' => $item['connection'], 'fields' => []
                        ];
                    }
                    $group[$row->table]['fields'][] = ['field' => $row->field, 'type' => $row->type, 'default' => $row->default, 'is_null' => $row->is_null, 'comment' => $row->comment, 'collation' => $row->collation,];
                }
                $dictionary[$database] = $group;
            }
            return $dictionary;
        });
    }


    /**
     * 获取数据表信息
     * @return array
     */
    public static function table(): array
    {
        $table = [];
        foreach (config('databases') as $name => $item) {
            $table[$item['database']] = [
                'database' => $item['database'],
                'connection' => $name,
                'list' => DB::connection($name)->select('SHOW TABLE STATUS')
            ];
        }
        return $table;
    }
}